package net.suncaper.demo.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import net.suncaper.demo.domain.Hotel;
import net.suncaper.demo.domain.Order;
import net.suncaper.demo.domain.RoomType;
import net.suncaper.demo.domain.User;
import net.suncaper.demo.service.OrderService;
import net.suncaper.demo.service.RoomTypeService;
import net.suncaper.demo.service.RestService;
import net.suncaper.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RoomTypeService roomTypeService;
    @Autowired
    private  RestService restService;

    @Autowired
    private  UserService userService;

    @RequestMapping
    public String OrderPages(HttpServletRequest request,Model model){
        HttpSession session=request.getSession();
        Long userid = (Long)session.getAttribute("userID");
        List<Order> ordersBook = orderService.selectByStatus("未支付",userid);
        List<Order> ordersCompleted = orderService.selectByStatus("已支付",userid);
        List<Order> ordersConfirm = orderService.selectByStatus("已支付",userid);
        List<Order> ordersCancel = orderService.selectByStatus("取消",userid);
        model.addAttribute("ordersBook",ordersBook);
        model.addAttribute("ordersCompleted",ordersCompleted);
        model.addAttribute("ordersConfirm",ordersConfirm);
        model.addAttribute("ordersCancel",ordersCancel);
        return "pages/order/orderList.html";
    }

    @GetMapping("/create/test")
    public String OrderCreatePages_pre(HttpServletRequest request){
        return "pages/order/orderCreate_test.html";
    }

    @GetMapping("/create")
    public String OrderCreatePages(HttpServletRequest request,Model model, @RequestParam("hotelid") Long hotelid, @RequestParam("roomid") Long  roomid, @RequestParam("cityid") Long cityid){
        if(request.getSession().getAttribute("userID")==null)return "/pages/user/login.html";
        List<RoomType> roomType = roomTypeService.selectByPrimaryKey(hotelid,roomid,cityid);
        model.addAttribute("roomType",roomType.get(0));
        model.addAttribute("cityid",cityid);
        return "pages/order/orderCreate.html";
    }

    @PostMapping("/create")
    public String saveOrders(HttpServletRequest request,Order order, @RequestParam("cityid") Long cityid){
        //生成下单时间
        Calendar calendar= Calendar.getInstance();
        Date date=calendar.getTime();
        order.setOrdertime(date);
        HttpSession session=request.getSession();
        order.setOrderid(null);
        order.setUserid((Long) session.getAttribute("userID"));
        order.setStatus("未支付");

        orderService.saveOrder(order);
        return "redirect:/order";
    }

    @RequestMapping("/search")//返回json
    @ResponseBody
    public List<Order> findOrder(){
        return orderService.findOrder();
    }

    @GetMapping("/view/{orderId}")
    public  String OrderViewPages(@PathVariable("orderId") long id,Model model){
        Order order=orderService.selectByPrimaryKey(id);
        model.addAttribute("order",order);

        String[] DateCheckIn = new SimpleDateFormat("yyyy-MM-dd").format(order.getCheckin()).toString().split("-");
        String[] DateCheckout = new SimpleDateFormat("yyyy-MM-dd").format(order.getCheckout()).toString().split("-");
        model.addAttribute("DateCheckIn",DateCheckIn);
        model.addAttribute("DateCheckout",DateCheckout);
        long hotelID=order.getHotelid();
        long roomId=order.getRoomid();
        long cityid = order.getCityid();
        List<RoomType> roomType= roomTypeService.selectByPrimaryKey(hotelID,roomId,cityid);
        model.addAttribute("roomType",roomType.get(0));
        return "/pages/order/Orderview.html";
    }

    @PostMapping("/cancel")
    public String orderCancel(@RequestParam("orderid") Long orderid){
        Order order = orderService.selectByPrimaryKey(orderid);
        String policy = order.getPolicy();
        if(policy.equals("可取消")){
            order.setStatus("已取消");
            orderService.cancel(order);
            return"redirect:/order";
        }
        else{
            return"pages/order/cancelfailed.html";
        }

    }
    @GetMapping("/pay/{orderId}")
    public void alipay(@PathVariable("orderId")Long orderId, HttpServletResponse response)throws ServletException, IOException {
        Order order = orderService.selectByPrimaryKey(orderId);
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2016101100659083",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrISfXncrtylAoWirXFGOY5vWlElejnyISSUIf9bRBtbYSzRXRm73fl7Ggt2gQGtWhoSUs9byQWzBatbSPUlELvGAqyIYd6F4Xxt327hAv3+s8QO0YnZkZ4VzCPvKwmrWQ6BvdGPVhehNxTeWggsenbPfqLRbSzqqi6eIHCm7cCI9FVVponZSoNuejPbmzTM5SrygdykrBirBTsgGRCGomFHeKyg52TOw8rXVPo+mrY+tuAosfKCqAaARS7o9dfty6nmXDZsKKqtfuu5cw6V7kk2Lh1RABVdLUdNjrjsNuGz2bxZRTWVfTqxX6c7+zE3Bx5ghsiwbmgxXbJnC6vZA9AgMBAAECggEAHs3gEyL3RWiWlzzr2z1zVDG25BjyJ6TciDghrAkZgn6IIMhD9jA3tIjk045QMB30eJy+SWKOp9mSUbHFp8rkhd1J3kmsQrPyRAtrJyjhRwzilj0FsNmllpAHl3unSfz/U+9EHL+CZCKKX2nrPMJt2Ah4c/Hb2uSSuLKrGiNZo0emiJL7J/tDPhTqUNaXoYf3fA4Qfxgf/atv0pSjOJJMEhy2UCxbzdSp1lcUAbvgkTC6MvY8yi9yKWGzyLI51fTF+FCWAh64eHasspdCJnltEzbRtmM6IhGAgCVq2F7mwhc4QugkgO9AODPqZ4BnrXXm9CSPzn6607Wh+ozJMafgIQKBgQD7lro/KVcSq3wPHJZX7y55W/9/cjYNHypCLfa+5LLWnQlfqUPB64W5Z+94CLIpDGyPvuaP5Yl91pVMXaBl8khjLVLQv8OiU6pQLx6gZ5FLL3Q08qLIWjMv9kwIRAKoJT3qnC9/CaC3HBXAvbYAC+c+pcucT2sSzkqLPWL0L5rESQKBgQCuIUgQkkU+iOlGrsepdi3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1xXGDNQIDAQAB",
                "RSA2"); //获得初始化的AlipayClient

        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://localhost:8280/order/payresult/"+orderId+"/");//在公共参数中设置回跳地址
//        alipayRequest.setReturnUrl("http://domain.com/CallBack/return_url.jsp");
//        alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":" + "\"" + orderId+ "\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":" + "\"" + order.getOrderamount() + "\"," +
                "    \"subject\":" + "\"" + "酒店房间订单支付" + "\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"" +
                "  }");//填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }
    @RequestMapping("/payresult/{orderid}")
    public String returnUrl(Model model,HttpServletRequest request,@PathVariable("orderid") Long orderid) throws UnsupportedEncodingException, AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do",
                "2016101100659083",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrISfXncrtylAoWirXFGOY5vWlElejnyISSUIf9bRBtbYSzRXRm73fl7Ggt2gQGtWhoSUs9byQWzBatbSPUlELvGAqyIYd6F4Xxt327hAv3+s8QO0YnZkZ4VzCPvKwmrWQ6BvdGPVhehNxTeWggsenbPfqLRbSzqqi6eIHCm7cCI9FVVponZSoNuejPbmzTM5SrygdykrBirBTsgGRCGomFHeKyg52TOw8rXVPo+mrY+tuAosfKCqAaARS7o9dfty6nmX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qFs0ynPaXlHlN2XOiGxLxeaRmU1suGqZKBTsO/emRWhSyi5LZpi5kHGKgWEChjGue5AoGADeHWLfcK3LWU98KJicPvSqSt15b+SnXNZJS3jhPmZRgyb40ckhXm1qTkA0si9qlBjrsBf4h5HoEOnzY0ZlpRMaBcGQzlH42GJv5wFcyrgIYpDhrnqRXy+SfcN1ep+2+zFhMTYgdjAlptarNBpX/4Jm4HobBNiwLdt9QQxya83/E=",
                "JSON",
                "utf-8",
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqj4k/kfQPyXHl3yqcVx6XNuEpmO4GyNDB4DqMDX20ZBSTEKZg9NFKyHUxkvjmL4TILLuexT62objQ3wW185Wd8HUMUZlOANwOvCsFp5dN0DJj91odm7GAD/nfwxKLUSH/aA8OtkMTvpYI5YGj96crXT2u1HoJ6Z8erSaBAyqPx+grctSsAH1HF8gmo/JPvkwzsfIbhpj+GpOIpjsTYB2/0a0MaX8QJaG3mzWWqU1hjZ/TjOoPoXfAuHikGc6AlzTLDuQ4oWduV/SwBIZpkTL6TIEBoxUpTVM2ZVcNilzfA+jKHeEmoevwU8Kv/rVSvsIsqIQdrNafvg9sef1xXGDNQIDAQAB",
                "RSA2"); //获得初始化的AlipayClient
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();//创建API对应的request
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"" + orderid + "\"" +
                "  }");
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(alipayRequest);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if (response.getTradeStatus() == null)
        { System.out.println("fail！");
            return "redirect:/hotel/search";}
        if (response.getTradeStatus().equals("TRADE_SUCCESS")) {

            orderService.updateStatus(orderid);
            Order order=orderService.selectByPrimaryKey(orderid);
            Date datein=order.getCheckin();
            Date dateout=order.getCheckout();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String timein = format.format(datein);
            String timeout = format.format(dateout);
            Calendar c1 = Calendar.getInstance();
            c1.setTime(datein);
            Calendar c2 = Calendar.getInstance();
            c2.setTime(dateout);
            while(c1.compareTo(c2)<0){
                restService.updateNum(order.getCityid(),order.getHotelid(),order.getRoomid(),"'"+format.format(c1.getTime())+"'");
                c1.add(Calendar.DAY_OF_MONTH, 1);
            }
            System.out.println("成功！");
            HttpSession session=request.getSession();
            Long userid = (Long)session.getAttribute("userID");
            User user = userService.selectByPrimaryKey(userid);
            if(user.getBirthday()!=null)
            { String birthday = format.format(user.getBirthday());
                model.addAttribute("birthday",birthday);
            }
            //System.out.println(birthday);

            List<Order> ordersBook = orderService.selectByStatus("未支付",userid);
            List<Order> ordersConfirm = orderService.selectByStatus("已支付",userid);
            model.addAttribute("user",user);
            model.addAttribute("ordersBook",ordersBook);
            model.addAttribute("ordersConfirm",ordersConfirm);



//            orderMapper.updateByPrimaryKey(order);
            return "/pages/user/user.html";
        }
        else{

            return"redirect:/hotel/search";
        }
    }
}
